package com.example.ucropdemo;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;

import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropFragment;
import com.yalantis.ucrop.UCropFragmentCallback;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;


// fragment和activity打开ucrop（activity）都是在onActivityResult处理，虽然fragment被弃用了，但还是可以用的
public class MainActivity extends AppCompatActivity {

//    private static final int OPEN_GALLERY_REQUEST_CODE = 234;  // 0到65535

    private ImageView fromGalleryImageView;

    private ImageView fromUCropImageView;

    private ActivityResultLauncher<String> getContent = registerForActivityResult(new ActivityResultContracts.GetContent(), new ActivityResultCallback<Uri>() {
        @Override
        public void onActivityResult(Uri result) {
            Log.i("选择的图片", "uri：" + result);
            fromGalleryImageView.setImageURI(result);
            // 打开ucrop
            openUCropActivity(result);
        }
    });

    // 路径要存在，不然会报错
    private static final String OUTPUT_PATH = Environment.getExternalStorageDirectory() + "/Pictures";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fromGalleryImageView = findViewById(R.id.imageView_fromGallery);
        fromUCropImageView = findViewById(R.id.imageView_fromUCrop);

        findViewById(R.id.button_fromAlbum).setOnClickListener(v -> {
            // 打开打开相册
//            Intent pickIntent = new Intent(Intent.ACTION_PICK, null);
            // 如果限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
//            pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//            startActivityForResult(pickIntent, OPEN_GALLERY_REQUEST_CODE);
            // startActivityForResult已经弃用，使用registerForActivityResult

            getContent.launch("image/*");
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /*if (requestCode == OPEN_GALLERY_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK && data != null) {
                Log.i("选择的图片", "uri：" + data.getData());
                *//*try {
                    // 显示选择的图片
                    InputStream inputStream = getContentResolver().openInputStream(data.getData());
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    fromGalleryImageView.setImageBitmap(bitmap);
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }*//*
                fromGalleryImageView.setImageURI(data.getData());
                // 打开ucrop
                openUCropActivity(data.getData());
            }
        }*/

        if (requestCode == UCrop.REQUEST_CROP) {
            if (resultCode == Activity.RESULT_OK && data != null) {
                final Uri resultUri = UCrop.getOutput(data);
                Log.i("得到的图片", "uri：" + resultUri);
                fromUCropImageView.setImageURI(resultUri);
            }
        }

        else if (resultCode == UCrop.RESULT_ERROR) {
            final Throwable cropError = UCrop.getError(data);
        }

    }

    /**
     * 使用UCrop进行图片剪裁
     *
     * @param uri
     */
    public void openUCropActivity(Uri uri) {

        UCrop.Options options = new UCrop.Options();
        options.setToolbarTitle("ucrop裁切demo");
        // 修改标题栏颜色
        options.setToolbarColor(getResources().getColor(R.color.teal_200));
        // 修改状态栏颜色
        options.setStatusBarColor(getResources().getColor(R.color.teal_700));
        // 隐藏底部工具
        options.setHideBottomControls(true);
        // 图片格式
        options.setCompressionFormat(Bitmap.CompressFormat.JPEG);
        // 设置最大缩放比例
        options.setMaxScaleMultiplier(3);
        // 设置图片压缩质量
        options.setCompressionQuality(100);
        // 是否让用户调整范围(默认false)，如果开启，可能会造成剪切的图片的长宽比不是设定的
        // 如果不开启，用户不能拖动选框，只能缩放图片
        options.setFreeStyleCropEnabled(false);
        // 设置图片质量[0, 100]
        options.setCompressionQuality(100);
        // 圆
        options.setCircleDimmedLayer(true);
        // 是否显示网格线
        options.setShowCropGrid(false);
        // ...


        // 设置源uri及目标uri
        Uri u = Uri.fromFile(new File(OUTPUT_PATH, System.currentTimeMillis() + ".jpg"));  // 路径要存在
        UCrop.of(uri, u)
                // 长宽比
                .withAspectRatio(1, 1)
                // 图片最大大小
                .withMaxResultSize(200, 200)
                // 配置参数
                .withOptions(options)
                .start(this);  // fragment就传入getContext和this
    }

}